package com.anrongtec.zcpt.manager;

import java.io.File;
import java.util.ArrayList;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.base.BaseActivity;
import com.anrongtec.zcpt.module.AppModel;
import com.anrongtec.zcpt.module.AppUpgrade;
import com.anrongtec.zcpt.service.AppUpgradeService;
import com.anrongtec.zcpt.util.SnackbarUtil;
import com.anrongtec.zcpt.util.Util;
import com.art.base.util.ApkUtils;
import com.art.base.util.FileUtils;
import com.lzy.okhttpserver.download.DownloadInfo;
import com.lzy.okhttpserver.download.DownloadManager;
import com.lzy.okhttpserver.download.DownloadService;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

/**
 * app升级更新页面
 * 
 * @author cxy
 *
 */
public class AppUpgradeActivity extends BaseActivity {
	private SwipeRefreshLayout swipe_refresh;
	private RecyclerView rv_upgrade;
	private ArrayList<AppModel> apps;
	private CommonAdapter<AppModel> adapter;
	private EmptyWrapper<AppUpgrade> emptyWrapper;

	private static final int STATE_NO_DATA = 1, STATE_UPDATE = 2;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case STATE_NO_DATA:
				emptyWrapper.setEmptyView(R.layout.empty_view);
				rv_upgrade.setAdapter(emptyWrapper);
				break;

			case STATE_UPDATE:
				emptyWrapper.notifyDataSetChanged();
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_app_upgrade);

		initViews();

		// initData();

	}

	@Override
	protected void onResume() {
		super.onResume();
		// 获取本地数据库存放的需要升级的app信息
		apps.clear();
		apps.addAll(AppUpgradeService.getNeedUpgreade());
		notifyData();

	}

	@Override
	protected void onCreateCustomToolBar(Toolbar toolbar) {
		toolbar.setTitle("应用升级");
		super.onCreateCustomToolBar(toolbar);
	}

	/*
	 * @Override protected void initData() { // List<AppModel> uploadApps =
	 * Util.getAppsInfo(AppUpgradeActivity.this); final List<AppModel>
	 * uploadApps = Util.getAppsFromMaket(AppUpgradeActivity.this);
	 * 
	 * String json = GsonUtil.toAppUpgradeJson(uploadApps); HttpUtil.post(json,
	 * new StringCallback() {
	 * 
	 * @Override public void onResponse(boolean arg0, String arg1, Request arg2,
	 * Response arg3) {
	 * 
	 * //*********************** //TODO 上报 查询应用更新信息 String accountId =
	 * PreferenceUtils.getInstance(AppUpgradeActivity.this).getString(
	 * PreferenceKey.ACCOUNT_ID); WLData.getInstance().reportEvent(accountId,
	 * Events.APP_UPGRADE_INFO); //***********************
	 * 
	 * JsonDataRestult<PageList<AppUpgrade>> result = GsonUtil.decode(arg1, new
	 * TypeToken<JsonDataRestult<PageList<AppUpgrade>>>(){}.getType()); if
	 * (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
	 * ArrayList<AppUpgrade> checkResut = result.getData().getCheckResut(); if
	 * (!Util.isEmpty(checkResut)) { //遍历结果,找出需要升级的app放入apps中 for (AppUpgrade
	 * upgrade : checkResut) { if (upgrade.isUpdate()) { // if (true) {
	 * //根据包名找到对应的app对象, 把远程得到的信息set进去
	 * 
	 * AppModel queryById =
	 * LiteOrmDBUtil.getLiteOrm().queryById(upgrade.getPkg(), AppModel.class);
	 * 
	 * // queryById.setLocalVersionCode();//本地版本号
	 * queryById.setRemoteVersionCode(upgrade.getExpVersionCode());//远程版本号
	 * queryById.setRemoteSize(upgrade.getExpSize()); apps.add(queryById); } }
	 * 
	 * notifyData(); }else { handler.sendEmptyMessage(STATE_NO_DATA); }
	 * 
	 * //保存需要更新的app信息 LiteOrmDBUtil.insertAll(checkResut);
	 * 
	 * //不管有没有都发广播 Intent intent = new Intent();
	 * intent.setAction(Constant.Action.APP_UPGRADE);
	 * intent.putExtra(Constant.DATA_APP_UPGRADE, apps); sendBroadcast(intent);
	 * 
	 * }else { ToastShow.shortMessage(result.getRetMsg());
	 * handler.sendEmptyMessage(STATE_NO_DATA); } }
	 * 
	 * @Override public void onError(boolean isFromCache, Call call, Response
	 * response, Exception e) { if (response == null) {
	 * ToastShow.shortMessage(getString(R.string.alert_failed_connect)); }
	 * 
	 * notifyData();
	 * 
	 * super.onError(isFromCache, call, response, e); } }); }
	 * 
	 */

	@Override
	protected void initViews() {
		initRecyclerView();

		// initSwipeRefresh();

	}

	/**
	 * 初始化下拉刷新
	 * 
	 * @param view
	 */
	private void initSwipeRefresh() {
		// swipe_refresh = (SwipeRefreshLayout)
		// findViewById(R.id.swipe_app_upgrade_refresh);
		swipe_refresh.setEnabled(false);
		swipe_refresh.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_orange_light,
				android.R.color.holo_green_light);
		swipe_refresh.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				initData();
			}
		});
	}

	// /**
	// * 是否显示refresh
	// * @param b
	// */
	// private void showRefresh(final boolean b){
	// swipe_refresh.post(new Runnable() {
	// @Override
	// public void run() {
	// swipe_refresh.setRefreshing(b);
	// }
	// });
	// }

	/**
	 * 初始化recyclerview
	 */
	private void initRecyclerView() {
		apps = new ArrayList<AppModel>();

		rv_upgrade = (RecyclerView) findViewById(R.id.rv_app_upgrade);
		rv_upgrade.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
		adapter = new CommonAdapter<AppModel>(this, R.layout.item_app_upgrade, apps) {
			@Override
			protected void convert(ViewHolder holder, final AppModel app, int position) {
				holder.setText(R.id.tv_item_app_upgrade_name, app.getAppName());
				// holder.setText(R.id.tv_item_app_upgrade_version_name,
				// app.getLocalVersionName() + " --- " +
				// app.getRemoteVersionName());
				holder.setText(R.id.tv_item_app_upgrade_version_name, app.getRemoteVersionCode() + "");
				holder.setText(R.id.tv_item_app_upgreade_total_size, "大小: " + Util.byte2Mega(app.getRemoteSize()));
				ImageLoader.getInstance().displayImage(app.getIconUrl(),
						(ImageView) holder.getView(R.id.iv_item_app_upgrade_icon));

				final Button btn_upgrade = holder.getView(R.id.btn_item_app_upgrade_upgrade);

				holder.setOnClickListener(R.id.btn_item_app_upgrade_upgrade, new OnClickListener() {
					@Override
					public void onClick(View v) {

						DownloadInfo info = DownloadService.getDownloadManager().getDownloadInfo(app.getUrl());
						if (info != null && info.getState() == DownloadManager.FINISH) {
							if (FileUtils.isExist(info.getTargetPath())) {
								// ApkUtils.install(AppUpgradeActivity.this, new
								// File(info.getTargetPath()));
								ApkUtils.installSilent(AppUpgradeActivity.this, new File(info.getTargetPath()));
							} else {
								APPDownloadManager.removeTask(info.getTaskKey());
								APPDownloadManager.addTask(AppUpgradeActivity.this, app, null);
								SnackbarUtil.showSnackbar(AppUpgradeActivity.this, btn_upgrade);
							}
						} else {
							APPDownloadManager.addTask(AppUpgradeActivity.this, app, null);
							SnackbarUtil.showSnackbar(AppUpgradeActivity.this, btn_upgrade);
						}
						// APPDownloadManager.addTask(AppUpgradeActivity.this,
						// app, null);
						// SnackbarUtil.showSnackbar(AppUpgradeActivity.this,
						// btn_upgrade);
					}
				});

			}
		};

		emptyWrapper = new EmptyWrapper(adapter);
		emptyWrapper.setEmptyView(R.layout.loading_view);
		// emptyWrapper.setEmptyView(R.layout.empty_view);

		rv_upgrade.setAdapter(emptyWrapper);
	}

	/**
	 * 更新数据
	 */
	private void notifyData() {
		if (adapter == null) {
			return;
		}
		if (Util.isEmpty(apps)) {
			handler.sendEmptyMessage(STATE_NO_DATA);
		} else {
			handler.sendEmptyMessage(STATE_UPDATE);
		}
	}
}
